package com.utils;

import com.alibaba.fastjson.JSON;
import com.annotation.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dao.SysUser;
import com.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author: madSong
 * @since: 2024/5/6
 * @description:
 */
@Component
@Slf4j
public class LoginUserResolver implements HandlerMethodArgumentResolver {
    @Resource
    private SysUserMapper sysUserMapper;
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        boolean b = methodParameter.hasParameterAnnotation(LoginUser.class) && methodParameter.getParameterType().isAssignableFrom(SysUser.class);
        return b;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String token = nativeWebRequest.getHeader("Authorization");
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if(ObjectUtils.isEmpty(stringObjectMap)){
            throw new RuntimeException("未登录");
        }
        SysUser sysUser;
        if(stringObjectMap.containsKey("userId")){
            Integer userId = (Integer)stringObjectMap.get("userId");
            sysUser = sysUserMapper.findBasicUserInfo(userId);
        }else {
            Object userInfo = stringObjectMap.get("userInfo");
            sysUser = JSON.parseObject(JSON.toJSONString(userInfo), SysUser.class);
        }
        return sysUser;
    }
}
